//
//  AccountModel.swift
//  Weibo
//
//  Created by mac on 16/1/14.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class AccountModel: NSObject,NSCoding {
    var access_token : String?
    var expires_in :NSTimeInterval = 0{
        didSet{
        olddate = NSDate(timeIntervalSinceNow: expires_in)
        
        }
    
    }
    var uid : String?
    var name: String?
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    var  olddate : NSDate?
    
    
     init(dict:[String : AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
     }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description : String {
     let keys = ["access_token","expires_in","uid","name","avatar_large"]
        let dict = self.dictionaryWithValuesForKeys(keys)
        return dict.description
     }
    
    func writetodefault(){
    
      let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
//        print(path)
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
   
   
    }
   class func loadaccount()->AccountModel?{
       let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let accout = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? AccountModel {
            if accout.olddate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
         
            
            return accout
            }
       
        }
         return nil
    }
     func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(olddate, forKey: "olddate")
 
    
    }
     required init?(coder aDecoder: NSCoder){
          expires_in =  aDecoder.decodeDoubleForKey("expires_in")
          access_token = aDecoder.decodeObjectForKey("access_token") as? String
          uid = aDecoder.decodeObjectForKey("uid") as? String
          name = aDecoder.decodeObjectForKey("name") as? String
          avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
           olddate = aDecoder.decodeObjectForKey("olddate") as? NSDate
    }
    
    
}
